package com.eaero.conf;

import com.eaero.CommonResp;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Validated异常返回
 * @author luofeng
 * @date 2022/8/8 13:10
 */
@RestControllerAdvice
public class ValidatedExceptionHandler {

    @ExceptionHandler({MethodArgumentNotValidException.class})
    public CommonResp handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
        return CommonResp.buildFailMsg(ex.getBindingResult().getFieldError().getDefaultMessage());
    }

    @ExceptionHandler({BindException.class})
    public CommonResp handleBindException(BindException ex) {
        return CommonResp.buildFailMsg(ex.getBindingResult().getFieldError().getDefaultMessage());
    }

    @ExceptionHandler({ConstraintViolationException.class})
    public CommonResp handleConstraintViolationException(ConstraintViolationException ex) {
        Set<ConstraintViolation<?>> violations = ex.getConstraintViolations();
        String message = violations.stream().map(ConstraintViolation::getMessage).collect(Collectors.joining(";"));
        return CommonResp.buildFailMsg(message);
    }

}
